from flask import Flask, render_template, request, jsonify
import serial.tools.list_ports
from utils.Logger import LogUtils

import random
def generate_random_data(length=5, min_value=10000, max_value=100000):
    return [random.randint(min_value, max_value) for _ in range(length)]

ser = None
# ser = serial.Serial(port="COM6",baudrate=115200,timeout=1)
app = Flask(__name__)
logger = LogUtils().get_log()

# 初始化8个灯的状态，全部为关闭
lights_status = [False] * 11
lights_status[1] = True
lights_status[8] = True
lights_status[9] = True
button_status = [False] * 17

def ser_write(ser,index):
    global button_status
    
    button_status[index] = not button_status[index]#默认了一个去更改灯的逻辑
    logger.info(f"button_status:{button_status}")

    binary_string = ''.join(['1' if status else '0' for status in button_status])
    binary_string = binary_string[::-1].zfill(32)

    hex_string = hex(int(binary_string, 2))[2:].upper()  # 去掉'0b'前缀并转换为大写
    hex_string = hex_string.zfill(8)
    print(hex_string)
    hex_string = 'AA' + hex_string[2:]
    byte_data = bytes.fromhex(hex_string)
    if ser and ser.is_open:#4个按键发送数据，处理按键发送数据的逻辑
        ser.write(byte_data)
        logger.info(f"按键{index}发送数据{byte_data},对应的2进制为{binary_string}!")
@app.route('/')
def home():
    return render_template('index.html')
    # return render_template('setting.html')
@app.route('/search_serial_ports', methods=['GET'])
def search_serial_ports():
    ports = [port.description for port in serial.tools.list_ports.comports()]
    return jsonify({'ports': ports})

@app.route('/connect_serial_port', methods=['POST'])
def connect_serial_port():
    data = request.json
    port = data['port']
    global ser
    try:
        import re
        match = re.search(r'COM(\d+)', port)

        # 如果找到匹配项，则提取并打印
        if match:
            com_number = match.group(1)
            port = f"COM{com_number}"
            ser = serial.Serial(port,baudrate=921600,timeout=1)
            logger.info({"ser":port})
            return jsonify({'status': 'Connected'})
        else:
           logger.error({"error":port})
    except serial.SerialException:
        ser = None
        return jsonify({'status': 'Failed to connect'})

@app.route('/update_light', methods=['POST'])
def update_light():
    data = request.json
    index = data['index']
    
    try:
        ser_write(ser,index-1)
        return jsonify(success=True, button_status=button_status)
    except:
        return jsonify(success=False, button_status=button_status)

@app.route('/special_action', methods=['POST'])
def special_action():
    action = request.json['action']
    try:
        ser_write(ser,action)
        return jsonify(success=True, action=action)
    except:
         return jsonify(success=False, action=-1)


@app.route('/numberListData', methods=['POST','GET'])
def numberListData():
    # 生成随机数据
    data1 = generate_random_data()
    data2 = generate_random_data()
    
    # 构建结果字典
    resDict = {
        "data1": data1,
        "data2": data2
    }
    
    # 返回JSON响应
    return jsonify(resDict)

@app.route('/get_lights_status', methods=['POST','GET'])
def get_lights_status():
    global lights_status
    # for i in range(11):
    #     lights_status[i] = not lights_status[i]
    if ser and ser.is_open:
        try:
            if ser.in_waiting > 0:
                buffer_size = 4
                received_data = ser.read(buffer_size)

                # 将接收到的数据转换为十六进制字符串
                hex_string = received_data.hex().upper()

                # 将十六进制字符串转换为二进制字符串
                bin_string = bin(int(hex_string, 16))[2:].zfill(32)

                # 取二进制字符串的最后11位
                relevant_bin_string = bin_string[-11:]

                # 更新 lights_status 列表
                for i in range(11):
                    lights_status[10-i] = relevant_bin_string[i] == '1'
                    # socketio.emit('update_lights', lights_status)
            
        except serial.SerialException:
            print("error")
    inverted_lights_status = [not status for status in lights_status]
    return jsonify(success=True,lights_status=inverted_lights_status)

if __name__ == '__main__':
    app.run(debug=True)
